from datetime import datetime
from typing import Union

def format_file_size(size_bytes: int) -> str:
    """格式化文件大小显示
    
    Args:
        size_bytes: 文件大小（字节）
    
    Returns:
        格式化的大小字符串
    """
    if size_bytes == 0:
        return "0 B"
    
    size_names = ["B", "KB", "MB", "GB", "TB"]
    i = 0
    size = float(size_bytes)
    
    while size >= 1024 and i < len(size_names) - 1:
        size /= 1024.0
        i += 1
    
    return f"{size:.2f} {size_names[i]}"

def format_timestamp(dt: Union[datetime, None]) -> str:
    """格式化时间戳显示
    
    Args:
        dt: 日期时间对象
    
    Returns:
        格式化的时间字符串
    """
    if dt is None:
        return "N/A"
    
    return dt.strftime("%Y-%m-%d %H:%M:%S")

def format_percentage(value: float, total: float) -> str:
    """格式化百分比显示
    
    Args:
        value: 数值
        total: 总值
    
    Returns:
        格式化的百分比字符串
    """
    if total == 0:
        return "0.00%"
    
    percentage = (value / total) * 100
    return f"{percentage:.2f}%"

def format_path(path: str, max_length: int = 80) -> str:
    """格式化路径显示，过长时截断
    
    Args:
        path: 文件路径
        max_length: 最大显示长度
    
    Returns:
        格式化的路径字符串
    """
    if len(path) <= max_length:
        return path
    
    # 保留文件名，截断路径部分
    parts = path.split('\\')
    if not parts:
        return path
    
    filename = parts[-1]
    remaining_length = max_length - len(filename) - 3  # 3 是 "..." 的长度
    
    if remaining_length <= 0:
        # 如果文件名本身就很长，就截取文件名
        return filename[:max_length - 3] + "..."
    
    # 从路径开始截取
    path_part = '\\'.join(parts[:-1])
    if len(path_part) > remaining_length:
        path_part = path_part[:remaining_length]
    
    return path_part + "..." + filename